﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SigowayCommonLib.ADO;
using WarehouseManager.Common;
using SigowayCommonLib;
using WarehouseManager.View;

namespace WarehouseManager
{
    public partial class PatientRegisterForm : Form
    {
        /// <summary>
        ///  操作员
        /// </summary>
        private string strOperator = string.Empty;

        /// <summary>
        ///  操作员
        /// </summary>
        private string strOperatorId = string.Empty;

        /// <summary>
        ///  操作日期
        /// </summary>
        private string strOperatDate = string.Empty;
        private DBManager dbManager;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_operator"></param>
        /// <param name="_operatid"></param>
        /// <param name="_operatdate"></param>
        public PatientRegisterForm(string _operator, string _operatid, string _operatdate)
        {
            InitializeComponent();
            this.strOperator = _operator;
            this.strOperatorId = _operatid;
            this.strOperatDate = _operatdate;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PatientRegisterForm_Load(object sender, EventArgs e)
        {
            try
            {
                Init();
            }
            catch(Exception ex)
            {
                MessageBoxHelp.ShowMsgError("患者信息设置画面启动失败,具体错误信息如下：\r\n" + ex.ToString());
                LogManager.WriteLine("者信息设置画面启动时，启动失败!Exception={0}", ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void Init()
        {
             //操作员
            this.lblOperator.Text = this.strOperator;
            //操作日期
            this.label16.Text = this.strOperatDate;

            ClearFormData(0);
            this.txtNum.Focus();
            dbManager = DBManager.GetDBManager();
        }
        /// <summary>
        /// 0 全清空 1：编号不清空
        /// </summary>
        /// <param name="flg"></param>
        private void ClearFormData(int flg)
        {
            switch (flg)
            {
                case 0:
                    this.txtNum.Clear();
                    this.txtName.Clear();
                    this.txtPinyin.Clear();
                    this.txtPhone.Clear();
                    this.txtAddress.Clear();
                    this.dateBirth.Text = DateTime.Now.ToString();
                    this.txtID.Clear();
                    this.comboxSex.Text = "";
                    this.txtCompany.Clear();
                    this.textComment.Clear();
                    this.dateInHospital.Text = DateTime.Now.ToString();
                    this.dateOutHospotail.Text = DateTime.Now.ToString();
                    this.txtDiseaseName.Clear();
                    this.lblID.Text = "";
                    break;
                case 1:
                    this.txtName.Clear();
                    this.txtPinyin.Clear();
                    this.txtPhone.Clear();
                    this.txtAddress.Clear();
                    this.dateBirth.Text = DateTime.Now.ToString();
                    this.txtID.Clear();
                    this.comboxSex.Text = "";
                    this.txtCompany.Clear();
                    this.textComment.Clear();
                    this.dateInHospital.Text = DateTime.Now.ToString();
                    this.dateOutHospotail.Text = DateTime.Now.ToString();
                    this.txtDiseaseName.Clear();
                    this.lblID.Text = "";
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtNum_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(txtNum.Text))
            {
                ClearFormData(1);
                return;
            }
            this.errorProvider.Clear();
            string sqlText = string.Format("SELECT * FROM PatientInfo WHERE Number = '{0}' ", this.txtNum.Text);
            try
            {
                DataTable datPatientInfo = this.dbManager.ExecuteQuery(new SQLObject(sqlText, null));
                if (datPatientInfo == null || datPatientInfo.Rows.Count < 1)
                {
                    ClearFormData(1);
                    return;
                }
                SetDataToForm(datPatientInfo);
            }
            catch (Exception ex)
            {
                MessageBoxHelp.ShowMsgError("编号取得失败,具体错误信息如下：\r\n" + ex.ToString());
                LogManager.WriteLine("编号取得时，取得失败!Exception={0}", ex);
            }
        }
     
        private void SetDataToForm(DataTable datPatientInfo)
        {
            this.txtNum.Text = datPatientInfo.Rows[0]["Number"] == null ?
                          string.Empty : datPatientInfo.Rows[0]["Number"].ToString();

            this.txtName.Text = datPatientInfo.Rows[0]["PatientName"] == null ?
                string.Empty : datPatientInfo.Rows[0]["PatientName"].ToString();

            this.txtPinyin.Text = datPatientInfo.Rows[0]["PYCode"] == null ?
                string.Empty : datPatientInfo.Rows[0]["PYCode"].ToString();

            this.txtPhone.Text = datPatientInfo.Rows[0]["MobileNo"] == null ?
                string.Empty : datPatientInfo.Rows[0]["MobileNo"].ToString();

            this.txtAddress.Text = datPatientInfo.Rows[0]["Addr"] == null ?
                string.Empty : datPatientInfo.Rows[0]["Addr"].ToString();

            this.dateBirth.Text = datPatientInfo.Rows[0]["birthday"] == null ?
                DateTime.Now.ToString() : datPatientInfo.Rows[0]["birthday"].ToString();

            this.txtID.Text = datPatientInfo.Rows[0]["PIDNumber"] == null ?
                string.Empty : datPatientInfo.Rows[0]["PIDNumber"].ToString();

            this.comboxSex.Text = (datPatientInfo.Rows[0]["Sex"] == null ?
                string.Empty : datPatientInfo.Rows[0]["Sex"].ToString()) == "1" ? "女" : "男";

            this.txtCompany.Text = datPatientInfo.Rows[0]["WorkPlace"] == null ?
                string.Empty : datPatientInfo.Rows[0]["WorkPlace"].ToString();

            this.textComment.Text = datPatientInfo.Rows[0]["Note"] == null ?
                string.Empty : datPatientInfo.Rows[0]["Note"].ToString();

            this.dateInHospital.Text = datPatientInfo.Rows[0]["RYDate"] == null ?
                DateTime.Now.ToString() : datPatientInfo.Rows[0]["RYDate"].ToString();

            this.dateOutHospotail.Text = datPatientInfo.Rows[0]["CYDate"] == null ?
                DateTime.Now.ToString() : datPatientInfo.Rows[0]["CYDate"].ToString();

            this.txtDiseaseName.Text = datPatientInfo.Rows[0]["SicknessName"] == null ?
                string.Empty : datPatientInfo.Rows[0]["SicknessName"].ToString();

            this.lblID.Text = datPatientInfo.Rows[0]["ID"] == null ?
                string.Empty : datPatientInfo.Rows[0]["ID"].ToString(); 
        }
        private void txtName_Validating(object sender, CancelEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtPinyin.Text))
            {
                this.errorProvider.Clear();
            }
        }

        private void txtPinyin_Validating(object sender, CancelEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtPinyin.Text))
            {
                this.errorProvider.Clear();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.txtNum.Text))
                {
                    this.errorProvider.SetError(this.txtNum, "请输入编号");
                    this.txtNum.Focus();
                    return;
                }
                this.errorProvider.Clear();
                if (string.IsNullOrEmpty(this.txtName.Text))
                {
                    this.errorProvider.SetError(this.txtName, "请输入姓名");
                    this.txtName.Focus();
                    return;
                }
                this.errorProvider.Clear();
                if (string.IsNullOrEmpty(this.txtPinyin.Text))
                {
                    this.errorProvider.SetError(this.txtPinyin, "请输入拼音码");
                    this.txtPinyin.Focus();
                    return;
                }
                this.errorProvider.Clear();
                if (string.IsNullOrEmpty(this.txtPhone.Text))
                {
                    this.errorProvider.SetError(this.txtPhone, "请输入联系电话");
                    this.txtPhone.Focus();
                    return;
                }
                //long lNum;
                //if (!long.TryParse(txtPhone.Text, out lNum))
                //{
                //    this.errorProvider.SetError(this.txtAddress, "联系电话请输数字");
                //    this.txtAddress.Focus();
                //    return;
                //}
                this.errorProvider.Clear();
                if (string.IsNullOrEmpty(this.txtAddress.Text))
                {
                    this.errorProvider.SetError(this.txtAddress, "请输入家庭住址");
                    this.txtAddress.Focus();
                    return;
                }
                this.errorProvider.Clear();
                if (string.IsNullOrEmpty(this.txtID.Text))
                {
                    this.errorProvider.SetError(this.txtID, "请输入身份证号码");
                    this.txtID.Focus();
                    return;
                }
                this.errorProvider.Clear();
                if (string.IsNullOrEmpty(this.comboxSex.Text))
                {
                    this.errorProvider.SetError(this.comboxSex, "请指定性别");
                    this.comboxSex.Focus();
                    return;
                }
                if (comboxSex.Text != "男" && comboxSex.Text != "女")
                {
                    this.errorProvider.SetError(this.comboxSex, "请指定性别为男或女");
                    this.comboxSex.Focus();
                    return;
                }
                this.errorProvider.Clear();
                int result = -1;
                string sqlText = string.Empty;
                if (string.IsNullOrEmpty(lblID.Text))
                {
                    sqlText = "INSERT INTO PatientInfo(Number,PatientName,PYCode,MobileNo,Addr,birthday,PIDNumber,Sex,WorkPlace,Note,RYDate,CYDate,SicknessName,CreateUser,CreateDate,UpdateUser,UpdateDate) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                    IDictionary<string, object> dicParameter = new Dictionary<string, object>();
                    dicParameter.Add("Number", this.txtNum.Text);
                    dicParameter.Add("PatientName", this.txtName.Text);
                    dicParameter.Add("PYCode", this.txtPinyin.Text);
                    dicParameter.Add("MobileNo", this.txtPhone.Text);
                    dicParameter.Add("Addr", this.txtAddress.Text);
                    dicParameter.Add("birthday", this.dateBirth.Value.ToString("yyyy-MM-dd"));
                    dicParameter.Add("PIDNumber", this.txtID.Text);
                    dicParameter.Add("Sex", this.comboxSex.Text == "女" ? "1" : "0");
                    dicParameter.Add("WorkPlace", this.txtCompany.Text);
                    dicParameter.Add("Note", this.textComment.Text);
                    dicParameter.Add("RYDate", this.dateInHospital.Value.ToString("yyyy-MM-dd"));
                    dicParameter.Add("CYDate", this.dateOutHospotail.Value.ToString("yyyy-MM-dd"));
                    dicParameter.Add("SicknessName", this.txtDiseaseName.Text);
                    dicParameter.Add("CreateUser", strOperatorId);
                    dicParameter.Add("CreateDate", DateTime.Now.ToString("yyyy-MM-dd"));
                    dicParameter.Add("UpdateUser", "");
                    dicParameter.Add("UpdateDate", "");
                    result = this.dbManager.ExecuteNonQueryAsync(new SQLObject(sqlText, dicParameter));
                }
                else
                {
                    sqlText = string.Format(@"Update PatientInfo set 
{0} = ?, 
{1} = ?, 
{2} = ?,
{3} = ?, 
{4} = ?, 
{5} = ?,
{6} = ?,
{7} = ?,
{8} = ?,
{9} = ?,
{10} = ?,
{11} = ?, 
{12} = ?,
{13} = ?,
{14} = ? 
where {15} = ?",
ConstInfo.COL_NUMBER,
ConstInfo.COL_PATIENT_NAME,
ConstInfo.COL_PYCODE,
ConstInfo.COL_MOBILENO,
ConstInfo.COL_ADDR,
ConstInfo.COL_BIRTHDAY,
ConstInfo.COL_PIDNUMBER,
ConstInfo.COL_SEX,
ConstInfo.COL_WORKPLACE,
ConstInfo.COL_NOTE,
ConstInfo.COL_RYDATE,
ConstInfo.COL_CYDATE,
ConstInfo.COL_SICKNESSNAME,
ConstInfo.COL_UPDATEUSER,
ConstInfo.COL_UPDATEDATE,
ConstInfo.COL_PATIENT_ID);
                    IDictionary<string, object> dicParameter = new Dictionary<string, object>();
                    dicParameter.Add(ConstInfo.COL_NUMBER, long.Parse(this.txtNum.Text));
                    dicParameter.Add(ConstInfo.COL_PATIENT_NAME, this.txtName.Text);
                    dicParameter.Add(ConstInfo.COL_PYCODE, this.txtPinyin.Text);
                    dicParameter.Add(ConstInfo.COL_MOBILENO, this.txtPhone.Text);
                    dicParameter.Add(ConstInfo.COL_ADDR, this.txtAddress.Text);
                    dicParameter.Add(ConstInfo.COL_BIRTHDAY, this.dateBirth.Value.ToString("yyyy-MM-dd"));
                    dicParameter.Add(ConstInfo.COL_PIDNUMBER, this.txtID.Text);
                    dicParameter.Add(ConstInfo.COL_SEX, this.comboxSex.Text == "女" ? "1" : "0");
                    dicParameter.Add(ConstInfo.COL_WORKPLACE, this.txtCompany.Text);
                    dicParameter.Add(ConstInfo.COL_NOTE, this.textComment.Text);
                    dicParameter.Add(ConstInfo.COL_RYDATE, this.dateInHospital.Value.ToString("yyyy-MM-dd"));
                    dicParameter.Add(ConstInfo.COL_CYDATE, this.dateOutHospotail.Value.ToString("yyyy-MM-dd"));
                    dicParameter.Add(ConstInfo.COL_SICKNESSNAME, this.txtDiseaseName.Text);
                    dicParameter.Add(ConstInfo.COL_UPDATEUSER, strOperatorId);
                    dicParameter.Add(ConstInfo.COL_UPDATEDATE, DateTimeUtil.GetCurrentDate());
                    dicParameter.Add(ConstInfo.COL_PATIENT_ID, lblID.Text);

                    result = this.dbManager.ExecuteNonQuery(new SQLObject(sqlText, dicParameter));
                }

                if (result == -1)
                {
                    MessageBoxHelp.ShowMsgError("保存失败,具体错误信息如下：\r\n" + sqlText);
                    LogManager.WriteLine("保存时，保存失败!保存SQL={0}", sqlText);
                    return;
                }
                MessageBoxHelp.ShowMsgInfor("保存成功");
                ClearFormData(0);
                this.txtNum.Focus();
                this.errorProvider.Clear();
            }
            catch (Exception ex)
            {
                MessageBoxHelp.ShowMsgError("保存失败,具体错误信息如下：\r\n" + ex.ToString());
                LogManager.WriteLine("保存时，保存失败!Exception={0}", ex);
            }
        }

        private void comboxSex_Validating(object sender, CancelEventArgs e)
        {
            if (comboxSex.Text != "男" && comboxSex.Text != "女")
            {
                this.errorProvider.SetError(this.comboxSex, "请输入正确的性别");
                return;
            }
            this.errorProvider.Clear();
        }

        private void txtNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }

        private void txtPhone_Validating(object sender, CancelEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtPhone.Text))
            {
                this.errorProvider.Clear();
            }
        }

        private void txtAddress_Validating(object sender, CancelEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtAddress.Text))
            {
                this.errorProvider.Clear();
            }
        }

        private void txtID_Validating(object sender, CancelEventArgs e)
        {
            if (!string.IsNullOrEmpty(txtID.Text))
            {
                this.errorProvider.Clear();
            }
        }

        private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            //{
            //    e.Handled = true;
            //}
        }

        private void btnSearchPaient_Click(object sender, EventArgs e)
        {
            SearchPatientForm SerachForm = new SearchPatientForm(strOperator);
            SerachForm.ShowDialog();
        }
    }
}
